//
//  AppState.swift
//  Kosspot
//
//  Created by 胡辉 on 2025/6/30.
//

import Foundation
import RxSwift
import RxCocoa
import SwiftUI
import UTEBluetoothRYApi
import Moya

class AppState: ObservableObject {
    static let shared = AppState()
    private let disposeBag = DisposeBag()
    
    
    @Published var isLoggedIn: Bool = TokenManager.shared.isLoggedIn
    @Published var currentUser: UserProfileResponse?
    @Published var isLoading = false
    @Published var error: String?
    
    // 导航
    @Published var navigationPath = NavigationPath()
    
    @Published var currentDevice: DeviceInfo?
    
    @Published var bleDelegate: BleDelegate = BleDelegate()
    @Published var bleManager: UTEBluetoothMgr = UTEBluetoothMgr.sharedInstance()
//    @Published var devices: [UTEModelDevice] = []
    @Published var errorMessage: String?
    @Published var showError: Bool = false
    @Published var showAlert: Bool = false

    
    private init() {
        if isLoggedIn {
            loadUserInfo()
        }
        if let lastDevice = DeviceManager.shared.lastConnectedDevice {
            currentDevice = lastDevice
        } else {
            if let last = DeviceManager.shared.devices.last {
                currentDevice = last
            }
        }
        
        bleManager.delegate = bleDelegate;
        DispatchQueue.main.asyncAfter(deadline: .now() + 2) { [self] in
            let  uuids = self.currentDevice?.mServicesConnectedUUID
            let connectedDeviceList: [UTEModelDevice] = self.bleManager.retrieveConnectedDevice(withServers: uuids) ?? []
            
            let connectedDevice = connectedDeviceList.first(where: { $0.identifier == currentDevice?.identifier })
            
            if connectedDevice != nil {
                bleManager.connect(connectedDevice)
            }
        }
        
        setupDeviceStatusChangeHandler()
    }
    
    
    
    
    func loadUserInfo () {
//        NetworkManager.shared.userprofile()
//            .observe(on: MainScheduler.instance)
//            .subscribe(
//                onSuccess: { [weak self] response in
//                    self?.isLoading = false
//                    self?.currentUser = response
//                },
//                onFailure: { [weak self] error in
//                    self?.isLoading = false
//                    self?.error = error.localizedDescription
//                    print(error);
//                }
//            )
//            .disposed(by: disposeBag)
        NetworkManager.shared.request(MultiTarget(ApiService.userProfile), responseType: UserProfileResponse.self)
            .observe(on: MainScheduler.instance)
            .subscribe(
                onNext: { [weak self] response in
                    self?.isLoading = false
                    print(response);
                    self?.currentUser = response
                },
                onError: { [weak self] error in
                    self?.handleError(error)
                    print(error);
                }
            )
            .disposed(by: disposeBag)
    }
    
    private func handleError(_ error: Error) {
        self.isLoading = false
        if let networkError = error as? NetworkError {
            self.error = networkError.errorDescription
//            if networkError.isAuthenticationError {
//                AppState.shared.logout()
//            }
        } else {
            self.error = error.localizedDescription
        }
    }
    
    func logout() {
        ///清除登录信息，token存的钥匙串删app不管用，要退出需要调用clear方法清除token
        TokenManager.shared.clear()
        isLoggedIn = false
        currentUser = nil
        UserConfigManager.shared.removeUserId()
        navigationPath.removeLast(navigationPath.count)
//        WeChatManager().revokeAuthorization(for: "wx1dee817c3798bf26")
    }
    
    
    func navigateTo(_ route: AppRoute) {
        navigationPath.append(route)
    }
    
    func navigateBack() {
        navigationPath.removeLast()
    }
    
    func navigateToRoot() {
        navigationPath.removeLast(navigationPath.count)
    }
    
    func navigateReplaceCurrent(to route: AppRoute) {
        if !navigationPath.isEmpty {
            navigationPath.removeLast()
        }
        navigationPath.append(route)
    }
    
    private func setupDeviceStatusChangeHandler() {
        bleDelegate.onDeviceStatusChanaged = { [weak self] newStatus in
            guard let self = self else { return }
            DispatchQueue.main.async {
                self.isLoading = false
            }
            
            if (newStatus == .connected) {
                if currentDevice != nil {
                    currentDevice?.isConnected = true
                    NotificationCenter.default.post(name: NSNotification.Name("BLEDeviceConnected"), object: nil)
                } else {
                    let account: String = "18888"
                    bleManager.mgrDevice.accountTool.phoneSendWatchAccount(with: account) { result, errorCode, uteDict in
                        DispatchQueue.main.async {
                            if errorCode == 100000 {
                                if result == 0 || errorCode == 2 {
                                    self.setupBT3Pair()
                                } else if result == 1 {
                                    //账号不一致
                                    self.bleManager.disconnectDevicesFromAccount()
                                }
                            }
                        }
                    
                    }
                }
            } else if (newStatus == .disconnected) {
                errorMessage = "已断开连接"
                showError = true
            } else if (newStatus == .connectingError) {
                showAlert = true
            }
        }
    }
    
    func setupBT3Pair() {
        let mgrDevice: UTEDeviceMgr? = bleManager.mgrDevice
        mgrDevice?.setBT3Pair(10000) { errorCode in
            if errorCode == 100000 {
                mgrDevice?.setBT3Info(1) { errCode in
                    if errCode == 100000 {
                        print("=------", errCode)
                    }
                }
            }
        }
    }
    
}


// MARK: - 蓝牙代理
class BleDelegate: NSObject, ObservableObject, UTEBluetoothDelegate {
    var onDeviceDiscovered: ((UTEModelDevice) -> Void)?
    
    var onDeviceStatusChanaged: ((UTEDevicesStatus) -> Void)?
    
    func uteDiscoverDevices(_ model: UTEModelDevice!) {
            if let device = model {
                if device.name == "MQ05" && device.advertisementAddress != nil {
                    DispatchQueue.main.async {
                        self.onDeviceDiscovered?(device)
                    }
                }
            }
        }
    
    func uteDevicesStatus(_ status: UTEDevicesStatus, error: (any Error)!, userInfo info: [AnyHashable : Any]! = [:]) {
        DispatchQueue.main.async {
            self.onDeviceStatusChanaged?(status)
        }
    }
    
    func uteANCSAuthorization(_ ancsAuthorized: Bool) {
        print("========", ancsAuthorized)
        /// 允许接受设备通知
    }
}


